package com.littlec.sdk.asynctask;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.json.JSONObject;

import android.content.Context;

import com.littlec.sdk.XMPPConnectionManager;
import com.littlec.sdk.listener.CMGroupListener;
import com.littlec.sdk.manager.CMGroupManager;
import com.littlec.sdk.manager.CMMessageManager;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.yinhai.activity.ChatAddGroupActivity;
import com.yinhai.asynctask.AsyncTaskContext;
import com.yinhai.asynctask.AsyncTaskForHttp;
import com.yinhai.asynctask.AsyncTaskForHttpProcess;
import com.yinhai.constant.Contact;
import com.yinhai.model.IMGroup;
import com.yinhai.model.IMUserGroup;
import com.yinhai.service.IMGroupServiceImpl;
import com.yinhai.service.IMUserGroupServiceImpl;

public class GroupTask extends AsyncTaskForHttp {

	String retStr = null;
	private Context context;
	private String groupName;
	private String createUserPhone;
	private Map<String, String> map;
	private String createUserName;
	CMGroupListener.OnAddGroupListener addGroupListener;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	// private ExecutorService executorService =
	// Executors.newFixedThreadPool(5);
	public GroupTask(Context context, String groupName, String createUserPhone,
			String createUserName, Map<String, String> map,CMGroupListener.OnAddGroupListener addGroupListener) {
		super(context, false);
		this.context = context;
		this.groupName = groupName;
		this.createUserPhone = createUserPhone;
		this.createUserName = createUserName;
		this.map = map;
		this.addGroupListener = addGroupListener;
	}

	public GroupTask(Context context, boolean autoForword) {
		super(context, autoForword);
	}

	public GroupTask(Context context, int timeoutRequestCount,
			boolean autoForword) {
		super(context, timeoutRequestCount, autoForword);
	}

	@Override
	protected void parse(Map<String, Object> result){
		this.retStr = (String) result.get(AsyncTaskContext.RESPONSE_CONTENT);
		JSONObject jo;
		try {
			jo = new JSONObject(retStr);
			if ("0".equals(jo.getString("status"))) {
				Message message = null;
				Iterator<String> iterator = map.keySet().iterator();
				String key = "";
				String groupId = jo.getString("data");
				while (iterator.hasNext()) {
					key = iterator.next();
					message = new Message();
					message.setProperty("systemMessage", "systemMessage");
					message.setProperty("groupId", groupId);
					message.setProperty("groupType", "1");// 1是添加，修改0是删除
					message.setProperty("groupName", groupName);
					message.setProperty("createUserPhone", createUserPhone);// 创建人
					message.setBody("");
					sendChatMessage(key, message);
				}
				saveGroupAndMembers(jo.getString("data"));
				addGroupListener.onSuccess(null, groupId);
				CMGroupManager.getInstance().groupMembers.remove(groupId);
			} else {
				addGroupListener.onFailed(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			addGroupListener.onFailed(null);
		}

	}

	public void saveGroupAndMembers(String groupId) {
		IMGroupServiceImpl imGroupService = new IMGroupServiceImpl(this.context);
		IMGroup group = new IMGroup();
		group.setGroupId(groupId);
		group.setGroupName(groupName);
		group.setUserPhone(createUserPhone);
		imGroupService.insert(group);
		IMUserGroupServiceImpl imUserGroupService = new IMUserGroupServiceImpl(
				context);
		IMUserGroup userGroup = null;
		Iterator<String> iterator = map.keySet().iterator();
		String key = "";
		userGroup = new IMUserGroup();
		userGroup.setGroupId(groupId);
		userGroup.setUserId(createUserPhone);
		userGroup.setUserName(createUserName);
		imUserGroupService.insert(userGroup);
		
		while (iterator.hasNext()) {
			key = iterator.next();
			userGroup = new IMUserGroup();
			userGroup.setGroupId(groupId);
			userGroup.setUserId(key);
			userGroup.setUserName(map.get(key) == null ? "" : map.get(key));
			imUserGroupService.insert(userGroup);
		}
	}

	private void sendChatMessage(final String to, final Message message) {
		this.executorService.submit(new Runnable() {
			public void run() {
				Chat chat = (Chat) CMMessageManager.getInstance().chats.get(to);
				XMPPConnection connection = XMPPConnectionManager.getInstance()
						.getConnection();
				if (connection == null) {
					return;
				}
				if (chat == null) {
					chat = XMPPConnectionManager.getInstance().getConnection()
							.getChatManager().createChat(to + "@" +

							XMPPConnectionManager.getInstance()

							.getConnection()

							.getServiceName(), null);
					CMMessageManager.getInstance().chats.put(to, chat);
				}
				if ((connection.isConnected())
						&& (connection.isAuthenticated())) {
					try {
						XMPPConnectionManager.getInstance().sendOnlinePacket();
						chat.sendMessage(message);
						return;
					} catch (Exception e) {
					}
				}
			}
		});
	}
}
